package my.study.javax.mail;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Ex01 {

	/**
	 * Java Mail Simple Test
	 * 
	 * @param args
	 * @throws MessagingException
	 * @throws UnknownHostException
	 * @throws AddressException
	 */
	public static void main(String[] args) throws AddressException,
			UnknownHostException, MessagingException {
		Properties props = new Properties();
		props.setProperty("mail.smtp.host", "mail-union-in.baidu.com");
		//props.setProperty("mail.smtp.auth", "false");
		props.setProperty("mail.from", "crm-autopost@baidu.com");
		props.setProperty("mail.to", "fanhongjie@baidu.com");

		String subject = "test";

		String content = "<a href=\"http://tieba.baidu.com\">贴&nbsp;吧</a> <input type=\"button\" value=\"百度一下\" \">";
		send(props, subject, content);

	}

	public static void send(Properties props, String subject, String content)
			throws AddressException, MessagingException, UnknownHostException {
		Transport transport = null;
		Session session = Session.getDefaultInstance(props);
		Message msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(props.getProperty("mail.from")));
		String mailto = props.getProperty("mail.to");
		String[] toAddr = mailto.split(",");
		Address[] addrs = new Address[toAddr.length];
		for (int i = 0; i < toAddr.length; ++i) {
			addrs[i] = new InternetAddress(toAddr[i]);
		}
		msg.setRecipients(Message.RecipientType.TO, addrs);

		msg.setSubject(subject);

		InetAddress localhost = InetAddress.getLocalHost();
		StringBuilder sb = new StringBuilder();
		sb.append("mail from :");
		sb.append(localhost.getHostName());
		sb.append("(ip:");
		sb.append(localhost.getHostAddress());
		sb.append(")\n");
		sb.append(content);
		MimeBodyPart part1 = new MimeBodyPart();
		DataHandler dataHandler = new DataHandler(content,
				"text/html; charset=utf-8");
		part1.setDataHandler(dataHandler);
		MimeMultipart mutilPart = new MimeMultipart();
		mutilPart.addBodyPart(part1);

		msg.setContent(mutilPart);

		msg.setSentDate(new Date());

		transport = session.getTransport("smtp");
		Transport.send(msg);

		System.out.println("mail has been sent");

	}

}
